<?
include_once('File.php');

class Dir {
	function replaceWithDirSeperator($needle,$path) {
		return str_replace($needle,DIRECTORY_SEPARATOR,$path);
	}
	function __construct($dir,$canonicalize=false,$allowRelativePath=false) {
		if (is_a($dir,'Dir'))
			$this->dir= $dir->getPath();
		else {
			$this->dir= $this->replaceWithDirSeperator('\\',$dir);
			// turn relative paths into canonicalized absolute pathname
			if ($canonicalize)
				$this->dir= realpath($this->dir);
			// strip trailing DIRECTORY_SEPARATOR
			if ($this->dir{(strlen($this->dir)-1)}== DIRECTORY_SEPARATOR)
				$this->dir= substr($this->dir,0,-1);
		}
	}
	function getPath() {
		return $this->dir;
	}
	function getDirname() {
		return basename($this->getPath());
	}
	function exists() {
		$dir= $this->getDirname();
		return is_dir($this->dir) && $dir!= '.' && $dir!= '..';
	}
	function create($mode) {
		$old = umask(0);
		$res= mkdir($this->getPath(),$mode);
		chmod($this->getPath(),$mode);
		umask($old);
		return $res;
	}
	function getSubDir($dirname) {
		return new Dir($this->getPath().DIRECTORY_SEPARATOR.$dirname);
	}
	function getFile($filename) {
		return new File($this->getPath().DIRECTORY_SEPARATOR.$filename);
	}
	function equals(Dir $dir) {
		return $this->getPath()=== $dir->getPath();
	}
	function __toString() {
		return $this->getPath();
	}
}